import axios from 'axios'
import router from '../../router'

let host
switch (process.env.NODE_ENV) {
  case 'development':// 开发环境
    host = 'http://127.0.0.1:11000/mall'
    break
  case 'alpha':// 测试环境
    host = 'http://127.0.0.1:11000/mall'
    break
  case 'production':// 生产环境
    host = 'https://fuwanlianwang.com/mall'
    break
  default:
}
export const baseUrl = host
axios.defaults.baseURL = baseUrl
window.BASE_URL = baseUrl

axios.defaults.timeout = 1000 * 15
axios.defaults.headers['Content-Type'] = 'application/json;charset=UTF-8'

export default (method, url, params) => {
  let adminInfo = window.localStorage.getItem('adminInfo')
  if (adminInfo) {
    adminInfo = JSON.parse(adminInfo)
    axios.defaults.headers['mall-token'] = adminInfo.token
  }
  method = method.toLowerCase()
  return new Promise((resolve, reject) => {
    axios({
      method,
      url,
      [method === 'get' ? 'params' : 'data']: params,
    }).then(resp => {
      resolve(resp.data)
    })
    .catch(err => {
      console.log(err.response.status)
      if (err.response.status === 1000) {
        router.push('/login')
      }
      reject(err.response.data)
    })
  })
}